<template>
  <div class="login-container">
    <a-card title="用户登录" style="width: 400px; margin: 100px auto;">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        @finish="handleLogin"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formState.username" placeholder="请输入用户名" />
        </a-form-item>
        
        <a-form-item label="密码" name="password">
          <a-input-password v-model:value="formState.password" placeholder="请输入密码" />
        </a-form-item>
        
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading" block>
            登录
          </a-button>
        </a-form-item>
        
        <a-form-item>
          <div style="text-align: center;">
            还没有账号？<a @click="goToRegister">立即注册</a>
          </div>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script>
export default {
  name: 'UserLogin'
}
</script>

<script setup>
import { reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import { userAPI } from '@/api/user'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref()
const loading = ref(false)

const formState = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  try {
    loading.value = true
    const res = await userAPI.login(formState.username, formState.password)
    const result = res.data // 后端统一返回 { code, message, data, success, timestamp }
    if (result?.success) {
      message.success('登录成功！')
      // data 为后端发放的 token
      localStorage.setItem('token', result.data)
      // 拉取当前用户与权限（通过 /api/auth/info，网关注入 X-User-Id）
      try {
        const infoRes = await request.get('/auth/info')
        const info = infoRes.data?.data
        let user = info?.user || {}
        
        // 追加拉取用户角色信息，便于前端识别 SYSTEM_ADMIN 等
        if (user && user.id) {
          try {
            const rolesResp = await request.get(`/roles/user/${user.id}`)
            const roles = Array.isArray(rolesResp?.data?.data) ? rolesResp.data.data : []
            user = { ...user, roles }
          } catch (_) {
            // 忽略角色拉取错误，保持已有信息
          }
        }
        
        if (user) {
          localStorage.setItem('userInfo', JSON.stringify(user))
        } else {
          localStorage.removeItem('userInfo')
        }
        const perms = Array.isArray(info?.permissions) ? info.permissions : []
        localStorage.setItem('userPermissions', JSON.stringify(perms))
      } catch (e) {
        localStorage.removeItem('userInfo')
        localStorage.setItem('userPermissions', JSON.stringify([]))
      }
      // 根据权限跳转：管理员进后台，普通用户回前台首页
      const user = JSON.parse(localStorage.getItem('userInfo') || '{}')
      const perms = JSON.parse(localStorage.getItem('userPermissions') || '[]')
      const isAdminAll = perms.includes('admin:all')
      const isSystemAdmin = Array.isArray(user?.roles) && user.roles.some(r => r.roleCode === 'SYSTEM_ADMIN')
      const isOperationAdmin = Array.isArray(user?.roles) && user.roles.some(r => r.roleCode === 'OPERATION_ADMIN')
      const canViewUsers = isAdminAll || isSystemAdmin || perms.includes('user:search')
      const canAccessBackend = canViewUsers || isOperationAdmin
      
      if (canAccessBackend) {
        // 管理员根据权限跳转到不同页面
        if (canViewUsers) {
          router.push('/hotel/users')
        } else if (isOperationAdmin) {
          router.push('/hotel/hotels')
        } else {
          router.push('/hotel')
        }
      } else {
        router.push('/')
      }
    } else {
      message.error(result?.message || '登录失败')
    }
  } catch (error) {
    message.error(error.response?.data?.message || '登录失败')
  } finally {
    loading.value = false
  }
}

const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: url('@/assets/xmjd.jpg') center/cover no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>